import Ember from 'ember';

export default Ember.Mixin.create({
  deleteHandler() {
      this.get('model').destroyRecord();
      this.gotoListView();
    },
    pluralModelName: Ember.computed('modelName', function() {
      var modelName = this.get('modelName');
      if (!modelName) {
        alert("please add 'modelName' property to list controller.");
      }
      return Ember.Inflector.inflector.pluralize(modelName);
    }),
    defaultMenuHandler(mname) {
      if (mname === 'delete') {
        this.deleteHandler();
      } else if (mname === 'gotolist') {
        this.gotoListView();
      }
    },
    gotoListView() {
      this.transitionToRoute(this.get('pluralModelName') + ".index");
    },
    _actions: function() { // doesn't work.
      return {
        descriptionFocused() {
          alert('Name is ' + this.get('name'));
        }
      };
    },
    parseAutoBack() {
      var autoBack = this.get('autoBack') || {
        create: true,
        edit: true
      };
      if (autoBack && Ember.typeOf(autoBack) === 'boolean') {
        return {
          create: true,
          edit: true
        };
      }
      return autoBack;
    },
    defaultFromHandler() {
      var model = this.get('model'),
        store = this.store,
        self = this,
        formState = this.get('formState'),
        err = model.validateMe();

      if (!formState.allowSubmit()) {
        return;
      }
      if (err) {
        formState.setError(err);
      } else {
        formState.startSaving();
        model.save().then(function() {
          formState.success();
          var autoBack = self.parseAutoBack();
          if (autoBack.create && self.get('isNewRecord')) {
            self.transitionTo(self.get('pluralModelName'));
            return;
          } else if (autoBack.edit && !self.get('isNewRecord')) {
            self.transitionTo(self.get('pluralModelName'));
            return;
          }
          if (self.get('isNewRecord')) {
            self.set('model', store.createRecord(self.get('modelName'), {}));
          } else {
            self.transitionTo(self.get('pluralModelName'));
          }
        }, function() {
          if (formState.is201(model.get('adapterError'))) {
            self.transitionTo(self.get('pluralModelName'));
          } else {
            formState.failure();
          }
        });
      }
    },
    commonMenus: [{
      name: 'gotolist',
      action: 'gotolist',
      label: '返回',
      showWhen: "always"
    }, {
      name: 'delete',
      action: "delete",
      label: "删除",
      showWhen: "always"
    }]
});
